// 文档 https://cn.vuejs.org/v2/guide/custom-directive.html

import Vue from 'vue'

//自动获取focus
Vue.directive('focus', {
    //被绑定元素插入父节点时调用
    inserted: function(el) { 
        el.focus()
    }
});

//失去焦点的时候
Vue.directive('restorelayui', {
    inserted: function(el) {
		var tagName = el.tagName.toLocaleLowerCase();
		var dom = el;
		if(tagName != 'input'){
			dom = el.querySelector("input");
		}
		if(tagName != 'input' && !dom){
			dom = el.querySelector("textarea");
		}
        dom.onblur=function(){
            Vue.$onBlurScrollTop =  setTimeout(function(){
				document.body.scrollTop=0;
                document.documentElement.scrollTop=0;
            },100); 
        }
        dom.onfocus=function(){
            clearInterval(Vue.$onBlurScrollTop);
        }
    }
});

//input 只能输入数值
Vue.directive('num', {
    update: function(el, binding, vnode, oldVnode) {
        var max=el.getAttribute("max");
        var min=el.getAttribute("min");
        var value=vnode.data.domProps.value;
        var expression=null;
        if(vnode.data.directives[0]){
            vnode.data.directives.map(function(h){
                if(h.name=="model"){ expression=h.expression}
            });
        }
        if(binding.expression){
           expression=expression.replace(binding.expression,binding.value);
        }
        if(expression){
            var _eval="";
            if(!Number(value) && value !=0 ){
                _eval="vnode.context."+expression+"="+(oldVnode.data.domProps.value || "''");
            }else{
                if(max && Number(value) > Number(max)){
                   _eval="vnode.context."+expression+"="+Number(max);
                }
                if(min && Number(value) < Number(min)){
                   _eval="vnode.context."+expression+"="+Number(min);
                }
            }
            eval(_eval);
        }
    }
});

//input 定位光标位置
Vue.directive('startEnd', {
    inserted: function(obj) { 
        obj.addEventListener("focus",function(){
            clearInterval(Vue.$onBlurScrollTop);
            var len = obj.value.length; 
            if (document.selection) { 
                var sel = obj.createTextRange(); 
                sel.moveStart('character',len); //设置开头的位置
                sel.collapse(); 
                sel.select(); 
            } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') { 
                obj.selectionStart = obj.selectionEnd = len;
            } 
        })
    }
});




